package com.example.springboot.condition;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.util.Map;

/**
 * @author: huangjiazhen
 * @create: 2023/1/11 18:09
 * @description: 真正的条件逻辑处理类
 **/
public class TestOnClassCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        // 通过注释拿到value属性
        Map<String, Object> annotationAttributes = metadata.getAnnotationAttributes(TestConditionOnClass.class.getName());
        String className = (String) annotationAttributes.get("value");

        try {
            // 用类加载器进行加载，能加载到则符合条件，否则不满足
            context.getClassLoader().loadClass(className);
            return true;
        } catch (ClassNotFoundException e) {
            return false;
        }
    }
}
